package com.mytest.rabbitMQ.Fourth;

import com.rabbitmq.client.*;

public class ReceiveLogsDirect {
    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        String queueName = channel.queueDeclare().getQueue();   // 随机生成队列
        String queueName1 = channel.queueDeclare().getQueue();

        // 模拟命令行提供参数
        //String[] arg = {};
        String[] arg = {"info", "warning", "error"};
        if (arg.length < 1) {
            System.err.println("Usage: ReceiveLogsDirect [info] [warning] [error]");
            System.exit(1);
        }

        // 交换机和队列绑定
        channel.queueBind(queueName, EXCHANGE_NAME, arg[2]);    // 把error绑在第一个队列
        // info和warning绑在第二个队列中
        channel.queueBind(queueName1, EXCHANGE_NAME, arg[0]);
        channel.queueBind(queueName1, EXCHANGE_NAME, arg[1]);

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" +
                    delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
        channel.basicConsume(queueName1, true, deliverCallback, consumerTag -> { });
    }
}
